package com.idriver.dao;

import com.idriver.bean.Admin;
import com.idriver.util.DBCPUtil;
import com.idriver.util.MD5Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AdminDaoImpl implements AdminDao {
    /**
     * 实现管理员登录
     * @param admin
     * @return
     */
    @Override
    public Admin login(Admin admin) {

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;

        try {
            //1. 获取数据库连接
            conn = DBCPUtil.getConnection();

            //2. 准备SQL语句, 获取预处理对象
            String sql = "select * from admin where name = ? and password = ?";
            ps = conn.prepareStatement(sql);

            //3. 设置占位符对应的查询内容
            ps.setString(1, admin.getName());
            ps.setString(2, MD5Util.getMD5String(admin.getPassword()));
            System.out.println(MD5Util.getMD5String(admin.getPassword()));

            //4. 执行查询, 获取结果集; 如果登录成功, 返回Admins对象
            resultSet = ps.executeQuery();
            if (resultSet.next()) {

                Admin adminLogin = new Admin(resultSet.getString("name"), resultSet.getString("password"));
                return adminLogin;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBCPUtil.close(conn, ps, resultSet);
        }

        return null;
    }
}
